package com.hkx.smipleemps.servlet;

import com.hkx.smipleemps.common.domain.Employee;
import com.hkx.smipleemps.common.utils.DateUtil;
import com.hkx.smipleemps.service.EmployeeService;
import com.hkx.smipleemps.service.EmployeeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/addEmployee.do")
public class AddEmployeeServlet extends HttpServlet {
    EmployeeService employeeService = new EmployeeServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            String name = request.getParameter("name").trim();
            String sexStr = request.getParameter("sex").trim();//0 1
            boolean sex = (Integer.parseInt(sexStr) == 1 ? true : false);
            String empNo = request.getParameter("empNo").trim();
            String job = request.getParameter("job").trim();
            String salStr = request.getParameter("sal").trim();//
            double sal = Double.parseDouble(salStr);// "88.9"  ---> 88.9
            Date birthday = DateUtil.parseDate(request.getParameter("birthday"));
            Date hireday = DateUtil.parseDate(request.getParameter("hireday"));
/*//          日期类型的转换 这些代码已经转移到工具类中
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = simpleDateFormat.parse(birthdayStr);
            Date hireday = simpleDateFormat.parse(hiredayStr);*/

            Employee employee = new Employee().setName(name).setSex(sex).setEmpNo(empNo).setJob(job).setSal(sal)
                     .setBirthday(birthday).setHireday(hireday);

            employeeService.addEmployee(employee);
            request.setAttribute("msg", "添加员工成功");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "添加失败");
        }
        request.getRequestDispatcher("/addEmployeeAfter.jsp").forward(request, response);
    }
}
